package com.bite.forum.services.impl;


import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.dao.ArticleMapper;
import com.bite.forum.exception.ApplicationException;
import com.bite.forum.model.Article;
import com.bite.forum.model.Board;
import com.bite.forum.model.User;
import com.bite.forum.services.IArticleService;
import com.bite.forum.services.IBoardService;
import com.bite.forum.services.IUserService;
import com.bite.forum.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;

    @Override
    public void create(Article article) {
        // 判断参数是否为空
        if (article == null || article.getUserId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }

        // 设置文章访问次数、回复次数、点赞次数、删除状态、状态、创建时间、更新时间
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        // 插入文章
        int row = articleMapper.insertSelective(article);
        if (row <= 0) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(ResultCode.FAILED_CREATE.toString());
        }

        // 根据文章的用户id查询用户
        User user = userService.selectById(article.getUserId());
        if (user == null) {
            log.warn(ResultCode.FAILED_CREATE + "，发帖失败，user id = " + article.getUserId());
            throw new ApplicationException(ResultCode.FAILED_CREATE.toString());
        }
        // 增加用户的发帖数量
        userService.addOneArticleCountById(user.getId());

        // 根据文章的板块id查询板块
        Board board = boardService.selectById(article.getBoardId());
        if (board == null) {
            log.warn(ResultCode.FAILED_CREATE + "，发帖失败，board id = " + article.getBoardId());
            throw new ApplicationException(ResultCode.FAILED_CREATE.toString());
        }
        // 增加板块的发帖数量
        boardService.addOneArticleCountById(board.getId());

        // 记录成功日志
        log.info(ResultCode.SUCCESS + ",user id = " + article.getUserId() +
                ",borad id = " + article.getBoardId() +
                ", article id = " + article.getId() + "发帖成功");
    }

    @Override
    public List<Article> selectAll() {
        // 调用DAO
        List<Article> articles = articleMapper.selectAll();
        // 返回结果
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 非空校验
        if (boardId == null || boardId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验版块是否存在
        Board board = boardService.selectById(boardId);
        if (board == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", board id = " + boardId);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 调用DAO，查询
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        // 返回结果
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        // 判断id是否为空或小于等于0
        if (id == null || id <= 0) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 根据id查询文章详情
        Article article = articleMapper.selectDetailById(id);

        if (article == null) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS + ", article id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 创建一个Article对象，用于更新文章浏览量
        Article update = new Article();
        // 设置文章id
        update.setId(article.getId());
        // 设置文章浏览量加1
        update.setVisitCount(article.getVisitCount() + 1);
        // 更新文章浏览量
        int row = articleMapper.updateByPrimaryKeySelective(update);

        // 判断更新是否成功
        if (row != 1) {
            // 记录警告日志
            log.warn(ResultCode.ERROR_SERVICES + "更新文章浏览量失败，article id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
        // 更新文章浏览量
        article.setVisitCount(article.getVisitCount() + 1);
        // 返回文章详情
        return article;
    }

    @Override
    public Article selectById(Long id) {
        // 判断id是否为空或小于等于0
        if (id == null || id <= 0) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据id查询文章
        return articleMapper.selectByPrimaryKey(id);
    }

    @Override
    public void modify(Long id, String title, String content) {
        // 判断参数是否为空
        if (id == null || id <= 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 创建新的文章对象
        Article newArticle = new Article();
        // 设置文章id
        newArticle.setId(id);
        // 设置文章标题
        newArticle.setTitle(title);
        // 设置文章内容
        newArticle.setContent(content);
        // 更新文章
        int row = articleMapper.updateByPrimaryKeySelective(newArticle);
        // 判断更新是否成功
        if (row != 1) {
            // 记录警告日志
            log.warn(ResultCode.ERROR_SERVICES + ", article id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void thumbsUoById(Long id) {
        // 判断id是否为空或小于等于0
        if (id == null || id <= 0) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 根据id查询文章
        Article article = articleMapper.selectByPrimaryKey(id);
        // 判断文章是否存在
        if (article == null) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 返回失败结果
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 判断文章是否被禁用或删除
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 返回失败结果
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 创建一个Article对象，用于更新文章点赞量
        Article newArticle = new Article();
        // 设置文章id
        newArticle.setId(article.getId());
        Date date = new Date();
        newArticle.setUpdateTime(date);
        // 设置文章点赞量加1
        newArticle.setLikeCount(article.getLikeCount() + 1);

        // 更新文章点赞量
        int row = articleMapper.updateByPrimaryKeySelective(newArticle);
        // 判断更新是否成功
        if (row != 1) {
            // 记录警告日志
            log.warn(ResultCode.ERROR_SERVICES + ", article id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void deleteById(Long id) {
        // 判断id是否为空或小于等于0
        if (id == null || id <= 0) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据id查询文章
        Article article = articleMapper.selectByPrimaryKey(id);

        // 判断文章是否存在
        if (article == null) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 返回失败结果
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 判断文章是否被禁用或删除
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 返回失败结果
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 创建一个Article对象，用于更新文章点赞量
        Article newArticle = new Article();
        // 设置文章id
        newArticle.setId(article.getId());
        Date date = new Date();
        newArticle.setUpdateTime(date);
        // 删除文章
        newArticle.setDeleteState((byte) 1);

        // 更新文章点赞量
        int row = articleMapper.updateByPrimaryKeySelective(newArticle);
        // 判断更新是否成功
        if (row != 1) {
            // 记录警告日志
            log.warn(ResultCode.ERROR_SERVICES + ", article id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        // 更新版块和用户的文章数量
        boardService.subOneArticleCountById(article.getBoardId());
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功,boardId = " + article.getBoardId() + ",userId = " + article.getUserId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        // 判断id是否为空或小于等于0
        if (id == null || id <= 0) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据id查询文章
        Article article = articleMapper.selectByPrimaryKey(id);

        // 判断文章是否存在
        if (article == null) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 返回失败结果
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 判断文章是否被禁用或删除
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 返回失败结果
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 创建一个Article对象，用于更新文章点赞量
        Article newArticle = new Article();
        // 设置文章id
        newArticle.setId(article.getId());
        Date date = new Date();
        newArticle.setUpdateTime(date);
        // 文章回复数加一
        newArticle.setReplyCount(article.getReplyCount() + 1);

        // 更新文章点赞量
        int row = articleMapper.updateByPrimaryKeySelective(newArticle);
        // 判断更新是否成功
        if (row != 1) {
            // 记录警告日志
            log.warn(ResultCode.ERROR_SERVICES + ", article id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        // 判断id是否为空或小于等于0
        if (userId == null || userId <= 0) {
            // 记录警告日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userService.selectById(userId);

        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        return articleMapper.selectByUserId(userId);
    }
}
